package com.barrett.hvzmoderator.com.barrett;


import java.util.ArrayList;

import org.alexd.jsonrpc.JSONRPCClient;
import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.barrett.hvzmoderator.R;


public class hvzmoderator extends TabActivity {
    
	private String sessid = "";
	Spanned rules;
	private Boolean listBuilt = false;
	final ArrayList<hvzplayer> playerIndex = new ArrayList<hvzplayer>();
	ArrayList<String> players = new ArrayList<String>();
	TabHost mTabHost;
	Context mainAct;
	ProgressDialog dialog;
	private Button login;
    private EditText user;
    private EditText pass;
    private ListView attendList;
    private ListView infoList;
    private TextView rulesContent;
	
	
	@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); }
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mainAct = this;
        
        mTabHost = getTabHost();
        
        login = (Button) findViewById(R.id.login_button);
        user = (EditText) findViewById(R.id.login_username);
        pass = (EditText) findViewById(R.id.login_password);
        
        attendList = (ListView) findViewById(R.id.attend_listview1);
        attendList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        attendList.setSaveEnabled(true);
        attendList.setTextFilterEnabled(true);
        
        infoList = (ListView) findViewById(R.id.info_listview);
        infoList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        infoList.setSaveEnabled(true);
        infoList.setTextFilterEnabled(true);
        rulesContent = (TextView) findViewById(R.id.rules_content);
        
        
        mTabHost.addTab(mTabHost.newTabSpec("login_tab").setIndicator("Login").setContent(R.id.LinearLayout01));
        mTabHost.addTab(mTabHost.newTabSpec("attendance_tab").setIndicator("Attendance").setContent(R.id.attend_linear));
        mTabHost.addTab(mTabHost.newTabSpec("info_tab").setIndicator("Player Info").setContent(R.id.info_linear));
        mTabHost.addTab(mTabHost.newTabSpec("rules_tab").setIndicator("Rules").setContent(R.id.rules_linear));
//        mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 45;
//        mTabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 45;
//        mTabHost.getTabWidget().getChildAt(2).getLayoutParams().height = 45;
//        mTabHost.getTabWidget().getChildAt(3).getLayoutParams().height = 45;
//        mTabHost.getTabWidget().getChildAt(4).getLayoutParams().height = 45;
        mTabHost.setCurrentTab(0);
        
        mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
			
			@Override
			public void onTabChanged(String tabId) {
				if (tabId=="login_tab"){
					
				}
				else if ((tabId=="info_tab") | tabId=="attendance_tab") {
					if ((sessid != "")&&(!listBuilt)){
						//get attendance and populate listview
						dialog = new ProgressDialog(mainAct);
						dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						dialog.setMessage("Loading...");
						dialog.setCancelable(false);
						dialog.show();
						dialog.setProgress(0);
						Thread t = new Thread() {
							public void run() {
								try {
									Log.v("hvz", "thread start");
									//fix players.getall
									JSONRPCClient client = JSONRPCClient.create("http://www.ohiostateugc.com/services/json-rpc");
									JSONArray result = client.callJSONArray("hvz.players.getall", sessid);
									
									Log.v("hvz", "Max " + result.length());
									Message msg1 = new Message();
									Bundle b1 = new Bundle();
									b1.putInt("prog", 1);
									msg1.setData(b1);
									mHandler.sendMessage(msg1);
									dialog.setMax(result.length());
									Log.v("hvz", "Max " + result.length());
									
									for(int i = 0; i < result.length(); i++) {
										
										Message msg1Loop = new Message();
										Bundle b1Loop = new Bundle();
										
										JSONObject playerObj = result.getJSONObject(i);
										Log.v("hvz", "i=" + i + " playerObj.name " + playerObj.getString("name") + dialog.getMax());
										hvzplayer obj = new hvzplayer(playerObj.getInt("uid"), 
												playerObj.getString("name"), 
												playerObj.getString("killid"), 
												playerObj.getInt("status"), 
												playerObj.getInt("tags"));
										obj.avatar = playerObj.getString("avatar");
										playerIndex.add(i, obj);
										players.add(i, obj.name);
										
										b1Loop.putInt("prog",i + 1);
										msg1Loop.setData(b1Loop);
										mHandler.sendMessage(msg1Loop);
									}
									
									
								} catch (Exception e) {
									String players[] = {e.toString()};
									Log.v("hvz", "EX" + e.toString());
//									attendList.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1 , players));
//									infoList.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1 , players));
//									attendList.setEnabled(false);
//									infoList.setEnabled(false);
								}
								Message msgEnd = new Message();
								Bundle bEnd = new Bundle();
								bEnd.putInt("prog", dialog.getMax());
								msgEnd.setData(bEnd);
								mHandler.sendMessage(msgEnd);
							}
						};
						t.start();
						
					}
					else if (!listBuilt) {
						String players[] = {"Not Logged In"};
						attendList.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1 , players));
						infoList.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1 , players));
						attendList.setEnabled(false);
						infoList.setEnabled(false);
					}
					
				}
				else if (tabId=="rules_tab"){
					dialog = new ProgressDialog(mainAct);
					dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					dialog.setMessage("Loading...");
					dialog.setCancelable(false);
					dialog.show();
					if (rules == null) {
						Log.v("hvz", "rules");
						Thread ruleThread = new Thread () {
							public void run () {


								JSONRPCClient client = JSONRPCClient.create("http://www.ohiostateugc.com/services/json-rpc");
								String ruleString;
								try {
									if(sessid == "") {
										String result = client.callJSONObject("system.connect").getString("sessid");
										ruleString =  client.callJSONObject("node.get", result, 27).getString("body");

									}
									else {
										ruleString =  client.callJSONObject("node.get", sessid, 27).getString("body");
									}
									//TODO
									//remove crap from result
								} catch (JSONRPCException e) {
									ruleString = e.toString();
								} 
								catch (JSONException e) {
									// TODO Auto-generated catch block
									ruleString = e.toString();
								}
								Bundle b = new Bundle();
								Message msg = new Message();
								b.putString("rules",ruleString);
								msg.setData(b);
								ruleHandler.sendMessage(msg);
								
							}
						};
						ruleThread.start();

					}
						
					
					
					
				}
			}
		});
        
        login.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				login.setEnabled(false);
				
				if(sessid == "") {//login
					dialog = new ProgressDialog(mainAct);
					dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					dialog.setMessage("Loading...");
					dialog.setCancelable(false);

					ugclogin(user.getText().toString(), pass.getText().toString());
					
				}
				else {//logout
					user.setEnabled(true);
					user.setText("");
					pass.setEnabled(true);
					pass.setText("");
					login.setText("Login");
					sessid = "";
					listBuilt = false;
					rules=null;
				}
				login.setEnabled(true);
			}
		});

        attendList.setOnItemClickListener(new ListView.OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int pos,
					long id) {
				CheckedTextView textView = (CheckedTextView)v;
				textView.setChecked(!textView.isChecked());
			}
        	
        });

        infoList.setOnItemClickListener(new ListView.OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int pos,
					long id) {
				
				hvzplayer player = playerIndex.get(pos);							
				
				Intent myIntent = new Intent(v.getContext(), hvzplayerinfo.class);
				

				myIntent.putExtra("player", player.toString());
				myIntent.putExtra("avatar", player.avatar);
				myIntent.putExtra("sessid", sessid);
                startActivityForResult(myIntent, 1);
				
			}
        	
        });
        
           
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	menu.clear();
    	if (sessid =="") return true;
    	MenuInflater inflater = getMenuInflater();
    	switch (mTabHost.getCurrentTab()) {
    	case 0:
    		break;
    	case 1:
            inflater.inflate(R.menu.menu_attend, menu);
            return true;
    		
    	case 2:
            inflater.inflate(R.menu.menu_info, menu);
            return true;
    		
    	case 3:
    		break;
    	case 4:
    		break;
    	}
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
    	switch (mTabHost.getCurrentTab()) {
	    	case 1:
	    		ListView attendList = (ListView) findViewById(R.id.attend_listview1);
	    	    switch (item.getItemId()) {
	    	    case R.id.attendMenuScan:
	    	    	Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	    	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	    	        startActivityForResult(intent, 2);	
	    	        return true;
	    	    case R.id.attendMenuReset:
	    	    	for (int i=0; i<playerIndex.size(); i++) {
	    				attendList.setItemChecked(i, false);
	    			}
	    	    	return true;
	    	    case R.id.attendMenuSubmit:
	    	    	SparseBooleanArray checked = attendList.getCheckedItemPositions();
	    	    	
	    			String output="";
	    			for (int i=0; i<playerIndex.size(); i++) {
	    				if(checked.get(i)) {
	    					hvzplayer player = playerIndex.get(i);
	    					if(output!=""){output += "|";}
	    					output += player.toString();
	    				}
	    			}
	    			Log.v("hvz", output);
	    			JSONRPCClient client = JSONRPCClient.create("http://www.ohiostateugc.com/services/json-rpc");
	    			try {
	    				Boolean result = client.callBoolean("hvz.players.present", sessid, output);
	    				if (!result) {
	    					throw new Exception("error");
	    				}
	    				else {
		    				AlertDialog.Builder builder = new AlertDialog.Builder(this);
		    	        	builder.setMessage("Success!")
		    	        	       .setCancelable(false)
		    	        	       .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
		    	        	           public void onClick(DialogInterface dialog, int id) {
		    	        	                dialog.dismiss();
		    	        	           }
		    	        	       });
		    	        	AlertDialog alert = builder.create();
		    	        	alert.show();
	    				}
	    			} catch (Exception e) {
	    				AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	        	builder.setMessage("Error" + e.toString())
	    	        	       .setCancelable(false)
	    	        	       .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
	    	        	           public void onClick(DialogInterface dialog, int id) {
	    	        	                dialog.dismiss();
	    	        	           }
	    	        	       });
	    	        	AlertDialog alert = builder.create();
	    	        	alert.show();
	    			}
	    		
	
	    	    	return true;
	    	    default:
	    	        return super.onOptionsItemSelected(item);
	    	    }
	    	
	    	case 2:
	    	{
	    		switch (item.getItemId()) {
	    	    case R.id.infoMenuScan:
	    	    	Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	    	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	    	        startActivityForResult(intent, 3);	
	    	        return true;
	    		}
	    	}
	    	default: return true;
    	}
    	
    	
    	
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	
    	switch (requestCode) {
    	case 1:
    		//
    		//PLAYER INFO PAGE REQUIRES NO RESULT ACTIONS
    		//
    		break;
    	case 2://scan for attendance
    		Log.v("scan", "returned attendance");
    		if (resultCode == RESULT_OK) {
    			//TODO
    			final ListView attendList = (ListView) findViewById(R.id.attend_listview1);
    			String contents = intent.getStringExtra("SCAN_RESULT");
    			
    			String [] atts = contents.split("\\|");

    			hvzplayer found = null;
    			boolean nameFound = false, idFound = false, zombie = false, duplicate = false;
    			int i = 0;
    			for(hvzplayer player:playerIndex) {

    				if (player.name.equals(atts[0])) {
    					nameFound = true;
    					if (player.killid.equals(atts[1])) {
    						idFound = true;
    						if (player.status == 2 | player.status == 3) {
    							zombie = true;
    						}
    						else if (attendList.isItemChecked(i)) {
    							duplicate = true;
    						}
    						else {
    							found = player;
    						}
    						break;
    					}

    				}
    				else if (player.killid.equals(atts[1])) {
    					idFound = true;
    				}
    				i++;
    			}
    			
    			String error = "";
    			if (found != null){
    				attendList.setItemChecked(i, true);
    				
    				final Intent myIntent = new Intent("com.google.zxing.client.android.SCAN");
        			myIntent.putExtra("SCAN_MODE", "QR_CODE_MODE");
    				startActivityForResult(myIntent, 2);
    			}
    			else {
    				if (zombie) {
    					error += "-PLAYER IS A ZOMBIE!!!!-\n";
    				}
    				if (duplicate) {
    					error += "-ID HAS ALREADY BEEN ENTERED-\n";
    				}
    				if (nameFound && !idFound) {
    					error += "-Incorrect Id for valid name-";
    				}
    				else if (idFound && !nameFound) {
    					error += "-Incorrect name for valid Id-";
    				}
    				else {
    					error = "-Both Name and ID don't exist-";
    				}
    				AlertDialog.Builder builder = new AlertDialog.Builder(this);
    				builder.setMessage("Error:\n" + error)
    				.setCancelable(false)
    				.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
    					public void onClick(DialogInterface dialog, int id) {
    						dialog.dismiss();
    					}
    				});
    				AlertDialog alert = builder.create();
    				final Intent intentAgain = new Intent("com.google.zxing.client.android.SCAN");
        			intentAgain.putExtra("SCAN_MODE", "QR_CODE_MODE");

        			alert.setOnDismissListener(new DialogInterface.OnDismissListener() {

        				@Override
        				public void onDismiss(DialogInterface dialog) {
        					// TODO Auto-generated method stub
        					startActivityForResult(intentAgain, 2);
        				}
        			});
    				alert.show();	
    			}

    			// Handle successful scan
    		} else if (resultCode == RESULT_CANCELED) {
    			// Handle cancel
    			Log.v("scan", "cancelled");
    			break;
    		}
    		break;
    	case 3: //scan for i
    		Log.v("scan", "returned player for info");
    		if (resultCode == RESULT_OK) {
    			//TODO
    			String contents = intent.getStringExtra("SCAN_RESULT");
    			String [] atts = contents.split("\\|");
    			hvzplayer found = null;
    			boolean nameFound = false, idFound = false, zombie = false;
    			for(hvzplayer player:playerIndex) {
    				
    				if (player.name.equals(atts[0])) {
    					nameFound = true;
    					if (player.killid.equals(atts[1])) {
    						idFound = true;
    						if (player.status == 2 | player.status == 3) {
    							zombie = true;
    						}
    						else {
    							found = player;
    						}
	    					break;
    					}
    					
    				}
    				else if (player.killid.equals(atts[1])) {
    					idFound = true;
    				}
    			}
    			String error = "";
    			if (found != null){
    				Intent myIntent = new Intent(getBaseContext(), hvzplayerinfo.class);
    				myIntent.putExtra("player", found.toString());
                    startActivityForResult(myIntent, 1);
    			}
    			else {
    				zombie = false;//Don't care about zombie status in player info section
    				if (zombie) {
    					error += "-PLAYER IS A ZOMBIE!!!!-\n";
    				}
    				if (nameFound && !idFound) {
    					error += "-Incorrect Id for valid name-";
    				}
    				else if (idFound && !nameFound) {
    					error += "-Incorrect name for valid Id-";
    				}
    				else {
    					error = "-Both Name and ID don't exist-";
    				}
        			AlertDialog.Builder builder = new AlertDialog.Builder(this);
        			builder.setMessage("Error:\n" + error)
        			.setCancelable(false)
        			.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dialog, int id) {
        					dialog.dismiss();
        				}
        			});
        			AlertDialog alert = builder.create();
        			alert.show();	
    			}
    			
    			// Handle successful scan
    		} else if (resultCode == RESULT_CANCELED) {
    			// Handle cancel
    			Log.v("scan", "cancelled");
    			Toast.makeText(getApplicationContext(), "Scanning Cancelled", Toast.LENGTH_SHORT).show();
    			break;
    		} 		
    		break;

    	}
    }

	void ugclogin(final String username, final String  password) {
		dialog.setProgress(0);
		dialog.show();	
    	Thread t = new Thread(){
    		public void run(){
				String result;
		    	JSONRPCClient client = JSONRPCClient.create("http://www.ohiostateugc.com/services/json-rpc");
		    	String output;
		    	
				try {
					result = client.callJSONObject("system.connect").getString("sessid");
					
					Message msg1 = new Message();
					Bundle b1 = new Bundle();
					b1.putInt("prog", 50);
					msg1.setData(b1);
					loginHandler.sendMessage(msg1);
			    	String sessid = result.toString().substring(8).split(",")[0];
			    	
			    	result =  client.callJSONObject("user.login", sessid, username, password).getString("sessid");
			    	Message msg2 = new Message();
					Bundle b2 = new Bundle();
			    	b2.putInt("prog", 90);
					msg2.setData(b2);
					msg2.recycle();
			    	
			    	output = result;
				} 
				catch (JSONRPCException e) {
					Log.v("hvz",e.toString());
					output = "exception";
				}
				catch (JSONException e) {
					Log.v("hvz",e.toString());
					output = "exception";
				}
				Message msg3 = new Message();
				Bundle b3 = new Bundle();
				b3.putString("output", output);
				b3.putInt("prog", 100);
				msg3.setData(b3);
				
				loginHandler.sendMessage(msg3);
    		}
    	};
    	t.start();
	}
	
	private Handler loginHandler = new Handler() {
//		  final Button login = (Button) findViewById(R.id.login_button);
//        final EditText user = (EditText) findViewById(R.id.login_username);
//        final EditText pass = (EditText) findViewById(R.id.login_password);
        
	      @Override
	      public void handleMessage(Message msg) {  
	    	  Bundle b = msg.getData();
	    	  
	    	  int prog = b.getInt("prog");
	    	  if(prog >= 100) {
	    		  String output = b.getString("output");
	    		  if (output != "exception"){
						sessid = output;
						login.setText("Log Out");
						user.setEnabled(false);
						pass.setEnabled(false);
						rules = null;
	    		  }
	    		  else {
	    			  login.setText("Error Logging In \nTry Again");
	    		  }
	    		  dialog.dismiss();
	    		  
	    	  }
	    	  else {
	    		  dialog.setProgress(prog);
	    	  
	    	  }
	    	  
	    	  	
	      }

	  };
	  
	  private Handler mHandler = new Handler(){
		  
		  @Override
	      public void handleMessage(Message msg) {  
			  Bundle b = msg.getData();
			  int prog = b.getInt("prog");
			  dialog.setProgress(prog);
			  if (prog == dialog.getMax()) {
				  dialog.dismiss();
				  attendList.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_checked , players));
				  infoList.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1 , players));
				  listBuilt = true;
				  attendList.setEnabled(true);
				  infoList.setEnabled(true);
			  }
		  }
	  };
	  private Handler ruleHandler = new Handler(){
		  
		  @Override
	      public void handleMessage(Message msg) {  
			  Bundle b = msg.getData();
			  String ruleString = b.getString("rules");
			  rules = Html.fromHtml(ruleString);
			  rulesContent.setText(rules);
			  dialog.dismiss();
		  }
	  };
	  
	  
}
